//
//  RealNameContentViewController.m
//  CYWFrame
//
//  Created by Oldfish on 2018/8/14.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "RealNameContentViewController.h"
#import <UIButton+WebCache.h>
#import "NSString+Common.h"
#import "PoiSearchPerKeywordController.h"
#import "TipViewController.h"

@interface RealNameContentViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) NSDictionary *realDict;
@property (nonatomic, assign) NSInteger imgTag;
@property (nonatomic, strong) NSMutableArray *imgStrArr;
@property (nonatomic, strong) UIImagePickerController *picker; // 照相机
@property (nonatomic, strong) NSNumber *lat;
@property (nonatomic, strong) NSNumber *lng;

@end

@implementation RealNameContentViewController {
    UIScrollView    *_scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self GETCertification];
    
    self.navigationItem.title = @"实名认证";
    self.view.backgroundColor = UISeparatedColorRGB;
    if ([self.roleToApply isEqual:@2]) {
        self.imgStrArr = [[NSMutableArray alloc] initWithObjects:@"0", @"1", @"2", nil];
    }
    else if([self.roleToApply isEqual:@3])
    {
        self.imgStrArr = [[NSMutableArray alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", nil];
    }
	else
	{
		self.imgStrArr = [[NSMutableArray alloc] initWithObjects:@"0", @"1", @"2", @"3", nil];
	}
	// 注册通知()
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLocate:)name:@"getLocate" object:nil];
	
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    _scrollView = [[UIScrollView alloc] init];
	[_scrollView setScrollEnabled:YES];
    [self.view addSubview:_scrollView];
    
    NSArray *arr;
    NSArray *placeArr;
    NSArray *imageArr;
    int line1Tag;   //拿来定位最后一条线的位置的tag，下面会获取这个tag对应的那条线
    
    if ([self.roleToApply isEqual: @2]) {
        arr = @[@"真实姓名", @"身份证号"];
        placeArr = @[@"请输入您的真实姓名", @"请输入您的身份证号"];
        line1Tag = 22;
    }
    else if([self.roleToApply isEqual: @3]){
        arr = @[@"店名", @"真实姓名", @"身份证号", @"营业执照编码", @"地址"];
        placeArr = @[@"请输入您的店名", @"请输入您的真实姓名", @"请输入您的身份证号", @"请输入您的营业执照编码", @"请输入您的店铺地址"];
        line1Tag = 25;
    }
    
    else {
        arr = @[@"公司全称", @"真实姓名", @"身份证号", @"营业执照编码"];
        placeArr = @[@"请输入公司全称", @"请输入您的真实姓名", @"请输入您的身份证号", @"请输入您的营业执照编码"];
        line1Tag = 24;
    }
    
    if (self.realDict) {
        if ([self.roleToApply isEqual:@2]) {
            placeArr = @[self.realDict[@"realname"], self.realDict[@"id_no"]];
        }
        else if([self.roleToApply isEqual:@3])
        {
            placeArr = @[self.realDict[@"name"], self.realDict[@"realname"], self.realDict[@"id_no"], self.realDict[@"license_coding"], self.realDict[@"address"]];
        }
        else if([self.roleToApply isEqual: @5])
        {
            placeArr = @[self.realDict[@"name"], self.realDict[@"realname"], self.realDict[@"id_no"], self.realDict[@"license_coding"]];
        }
        
        imageArr = self.imgStrArr;
    }
    
    CGSize size = [LZCTools textSizeWithText:@"测字数试测测" font:kUHSystemFontWithSize(14)];
    
    UIView *bgView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, arr.count*SW(8))];
    [_scrollView addSubview:bgView1];
    bgView1.backgroundColor = kWhiteColor;

    for (int i = 0; i < arr.count; i++) {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20+(40+size.height)*i, size.width, size.height)];
        [bgView1 addSubview:label];
        label.textColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = arr[i];
        label.font = kUHSystemFontWithSize(14);
        
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(20+size.width+10, 20+(size.height+40)*i, SCREEN_WIDTH-size.width-50, size.height)];
        [bgView1 addSubview:field];
        field.delegate = self;
        field.tag = 11+i;
//        field.placeholder = placeArr[i];
        field.textColor = [UIColor grayColor];
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        field.font = kUHSystemFontWithSize(14);
		if (i == 4) {
			UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
			field.rightView = imgV;
			field.rightViewMode = UITextFieldViewModeAlways;
			imgV.image = IMAGE(@"arrow_right_grey");
			[field addActionWithblock:^{
				//PoiSearchPerKeywordController *vc = [[PoiSearchPerKeywordController alloc] init];
				TipViewController *vc = [[TipViewController alloc] init];
				[self.navigationController pushViewController:vc animated:YES];
			}];
		}
        
        if (self.realDict) {
            
            field.text = placeArr[i];
            //            field.textAlignment = NSTextAlignmentRight;
            if ([self.realDict[@"audit"] isEqual:@"1"] || [self.realDict[@"audit"] isEqual:@"0"]) {
                field.userInteractionEnabled = NO;
				field.rightView.hidden = YES;
            }
        }
        else
            field.placeholder = placeArr[i];
        
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, label.y+label.height+20, SCREEN_WIDTH-40, 1)];
        [bgView1 addSubview:line];
        line.backgroundColor = UISeparatedColorRGB;
        line.tag = 21+i;
    }
    
    UIView *line1 = [self.view viewWithTag:line1Tag];
    
    bgView1.frame = CGRectMake(0, 10, SCREEN_WIDTH, line1.y);
    
    UIView *bgView2 = [[UIView alloc] init];
    [_scrollView addSubview:bgView2];
    bgView2.backgroundColor = kWhiteColor;
    
    UILabel *idL = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, size.height)];
    [bgView2 addSubview:idL];
    idL.textColor = [UIColor grayColor];
    idL.text = @"请按指定要求上传身份证照片";
    idL.font = kUHSystemFontWithSize(14);
    
    NSArray *imgArr = @[@"身份证正面", @"身份证反面", @"手持身份证"];
    
    CGFloat Y = 0.0f;
    
    for (int i = 0; i < imgArr.count; i++) {
        
        UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgView2 addSubview:imgBtn];
//        [imgBtn setBackgroundImage:[UIImage imageNamed:@"btn_add_jobpic"] forState:UIControlStateNormal];
        imgBtn.frame = CGRectMake(20+(SW(3)-10)*i, idL.y+size.height+10, SW(3)-20, SW(3)-20);
        imgBtn.tag = 31+i;
        [imgBtn addTarget:self action:@selector(picAction:) forControlEvents:UIControlEventTouchUpInside];
        Y = imgBtn.y+imgBtn.height+10;
        if (self.realDict) {
            [imgBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:imageArr[i]] forState:UIControlStateNormal];
            if ([self.realDict[@"audit"] isEqual:@"1"] ||
				[self.realDict[@"audit"] isEqual:@"0"]) {
                imgBtn.userInteractionEnabled = NO;
            }
        }
        else
            [imgBtn setBackgroundImage:[UIImage imageNamed:@"btn_add_jobpic"] forState:UIControlStateNormal];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20+(SW(3)-10)*i, Y, SW(3)-20, size.height)];
        [bgView2 addSubview:label];
        label.textColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = imgArr[i];
        label.font = kUHSystemFontWithSize(14);
    }
    
    bgView2.frame = CGRectMake(0, bgView1.y+bgView1.height+10, SCREEN_WIDTH, Y+20+size.height);
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, bgView2.y+bgView2.height+SH(8));
    
    //营业执照的View
    UIView *bgView3;
    if ([self.roleToApply isEqual:@3] || [self.roleToApply isEqual:@5]) {
        bgView3 = [[UIView alloc] init];
        [_scrollView addSubview:bgView3];
        bgView3.backgroundColor = kWhiteColor;
        
        UILabel *idL = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, size.height)];
        [bgView3 addSubview:idL];
        idL.textColor = [UIColor grayColor];
        idL.text = @"请上传营业执照照片";
        idL.font = kUHSystemFontWithSize(14);
        
        UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgView3 addSubview:imgBtn];
        imgBtn.frame = CGRectMake(20+(SW(3)-10), idL.y+size.height+10, SW(3)-20, SW(3)-20);
        imgBtn.tag = 34;
        [imgBtn addTarget:self action:@selector(picAction:) forControlEvents:UIControlEventTouchUpInside];
        Y = imgBtn.y+imgBtn.height+10;
        if (self.realDict) {
            [imgBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:imageArr[3]] forState:UIControlStateNormal];
			if ([self.realDict[@"audit"] isEqual:@"1"] ||
				[self.realDict[@"audit"] isEqual:@"0"]) {
                imgBtn.userInteractionEnabled = NO;
            }
        }
        else
            [imgBtn setBackgroundImage:[UIImage imageNamed:@"btn_add_jobpic"] forState:UIControlStateNormal];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20+(SW(3)-10), Y, SW(3)-20, size.height)];
        [bgView3 addSubview:label];
        label.textColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"上传/拍照";
        label.textColor = kRedColor;
        label.font = kUHSystemFontWithSize(14);
        bgView3.frame = CGRectMake(0, bgView2.y+bgView2.height+10, SCREEN_WIDTH, Y+20+size.height);
		_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, bgView3.y+bgView3.height+SH(8));
        
    }
	
	//商店Logo的View
	UIView *bgView4;
	if ([self.roleToApply isEqual:@3]) {
		bgView4 = [[UIView alloc] init];
		[_scrollView addSubview:bgView4];
		bgView4.backgroundColor = kWhiteColor;
		
		UILabel *idL = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, size.height)];
		[bgView4 addSubview:idL];
		idL.textColor = [UIColor grayColor];
		idL.text = @"请上传商店Logo";
		idL.font = kUHSystemFontWithSize(14);
		
		UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[bgView4 addSubview:imgBtn];
		imgBtn.frame = CGRectMake(20+(SW(3)-10), idL.y+size.height+10, SW(3)-20, SW(3)-20);
		imgBtn.tag = 35;
		[imgBtn addTarget:self action:@selector(picAction:) forControlEvents:UIControlEventTouchUpInside];
		Y = imgBtn.y+imgBtn.height+10;
		if (self.realDict) {
			[imgBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:imageArr.lastObject] forState:UIControlStateNormal];
			if ([self.realDict[@"audit"] isEqual:@"1"] ||
				[self.realDict[@"audit"] isEqual:@"0"]) {
				imgBtn.userInteractionEnabled = NO;
			}
		}
		else
			[imgBtn setBackgroundImage:[UIImage imageNamed:@"btn_add_jobpic"] forState:UIControlStateNormal];
		
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20+(SW(3)-10), Y, SW(3)-20, size.height)];
		[bgView4 addSubview:label];
		label.textColor = [UIColor grayColor];
		label.textAlignment = NSTextAlignmentCenter;
		label.text = @"上传/拍照";
		label.textColor = kRedColor;
		label.font = kUHSystemFontWithSize(14);
		bgView4.frame = CGRectMake(0, bgView3.y+bgView3.height+10, SCREEN_WIDTH, Y+20+size.height);
		_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, bgView4.y+bgView4.height+SH(8));
		bgView4.tag = 88;
		
	}
    
    UIButton *commitBtn;
    if (!self.realDict || [self.realDict[@"audit"] isEqual:@"2"]) {
        commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_scrollView addSubview:commitBtn];
        [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
        [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        CGFloat btnHeight = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+SW(20);
        if ([self.roleToApply isEqual:@3]) {
            commitBtn.frame = CGRectMake(20, bgView4.y+bgView4.height+20, SCREEN_WIDTH-40, btnHeight);
        }
		else if([self.roleToApply isEqual:@5])
		{
			 commitBtn.frame = CGRectMake(20, bgView3.y+bgView3.height+20, SCREEN_WIDTH-40, btnHeight);
		}
        else
            commitBtn.frame = CGRectMake(20, bgView2.y+bgView2.height+20, SCREEN_WIDTH-40, btnHeight);
        
        commitBtn.backgroundColor = UIMainColorRGB;
        commitBtn.layer.cornerRadius = 5;
        commitBtn.layer.masksToBounds = YES;
        [commitBtn addTarget:self action:@selector(completeAction:) forControlEvents:UIControlEventTouchUpInside];
		_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, commitBtn.y+commitBtn.height+SH(8));
    }

    _scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _scrollView.scrollEnabled = YES;
	NSLog(@"contentsize in buildUI is %lf,%lf",_scrollView.contentSize.width,_scrollView.contentSize.height);
}

#pragma mark ===========响应方法==========
- (void)GETCertification {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *param = @{@"role":self.roleToApply};

    [[NetworkTool sharedTool] requestWithName:@"获取认证信息" URLString:APIQueryCert parameters:param method:@"POST" callBack:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
       // id obj = [[JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode valueForKey:@"payload"];
        
        NSDictionary *dict = [responseObject valueForKey:@"data"];
        
		if (![dict isKindOfClass:[NSDictionary class]]) {
            [self presentViewController:[LZCTools alertMessage:@"您尚未申请该项认证"] animated:YES completion:nil];
        }
        else {
            self.realDict = dict;
            [self.imgStrArr removeAllObjects];
            //身份证的3张照片
            [self.imgStrArr addObject:dict[@"face_pic"]];
            [self.imgStrArr addObject:dict[@"unface_pic"]];
            [self.imgStrArr addObject:dict[@"real_pic"]];
			self.lat = dict[@"lat"];
			self.lng = dict[@"lng"];
            if ([self.roleToApply isEqual:@3] || [self.roleToApply isEqual:@5]) {
                [self.imgStrArr addObject:dict[@"license_pic"]];
				if ([self.roleToApply isEqual:@3]) {
					[self.imgStrArr addObject:dict[@"shop_logo"]];
				}
            }
            if ([dict[@"audit"] isEqual:@"0"]) {
                [self presentViewController:[LZCTools alertMessage:@"您的实名认证正在审核当中！"] animated:YES completion:nil];
            }
            else if ([dict[@"audit"] isEqual:@"1"]) {
				if ([self.roleToApply isEqual: @3]) {
					UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您的实名认证已通过，是否需要重新编辑提交？" message:nil preferredStyle:UIAlertControllerStyleAlert];
					[alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
					}]];
					[alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
						for (int i = 31; i <= 35; i++){
							UIButton *btn = (UIButton *)[self.view viewWithTag:i];
							btn.userInteractionEnabled = YES;
						}
						for (int i = 11; i <= 15; i++){
							UITextField *tf = (UITextField *)[self.view viewWithTag:i];
							tf.userInteractionEnabled = YES;
						}
						UIView *lastView = [self.view viewWithTag:88];
						UIButton *commitBtn;
						commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
						[_scrollView addSubview:commitBtn];
						[commitBtn setTitle:@"提交" forState:UIControlStateNormal];
						[commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
						CGFloat btnHeight = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+SW(20);
						commitBtn.frame = CGRectMake(20, lastView.y+lastView.height+20, SCREEN_WIDTH-40, btnHeight);
						commitBtn.backgroundColor = UIMainColorRGB;
						commitBtn.layer.cornerRadius = 5;
						commitBtn.layer.masksToBounds = YES;
						[commitBtn addTarget:self action:@selector(completeAction:) forControlEvents:UIControlEventTouchUpInside];
						_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, commitBtn.y+commitBtn.height+SH(8));
					}]];
					[self presentViewController:alert animated:YES completion:nil];
				}
				else {
					[self presentViewController:[LZCTools alertMessage:@"您的实名认证已通过"] animated:YES completion:nil];
				}
				
            }
            else if ([dict[@"audit"] isEqual:@"2"]){
				
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您的实名认证被拒绝" message:dict[@"reason"] preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"重新编辑" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
					NSLog(@"contentsize is %lf,%lf",_scrollView.contentSize.width,_scrollView.contentSize.height);
					
                }]];
				 
                [self presentViewController:alert animated:YES completion:nil];

            }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            [self buildUI];
            [self createImgPicker];
        });
    }];
}

- (void)completeAction:(id)sender {
    NSLog(@"提交响应");
    
	UITextField *realName;
	UITextField *idCard;
	UITextField *shopOrCompanyName;
	UITextField *address;
	UITextField *licenseCode;
	
	if ([self.roleToApply isEqual:@2]) {
		realName = [self.view viewWithTag:11];
		idCard = [self.view viewWithTag:12];
	}
	else if ([self.roleToApply isEqual:@3]) {
		shopOrCompanyName = [self.view viewWithTag:11];
		realName = [self.view viewWithTag:12];
		idCard = [self.view viewWithTag:13];
		licenseCode = [self.view viewWithTag:14];
		address = [self.view viewWithTag:15];
		
		// 店名不为空
		if ([NSString isEmpty:shopOrCompanyName.text]) {
			[self presentViewController:[LZCTools alertMessage:@"店名不可为空"] animated:YES completion:nil];
			return;
		}
		// 营业执照不为空
		if ([NSString isEmpty:licenseCode.text]) {
			[self presentViewController:[LZCTools alertMessage:@"营业执照编码不可为空"] animated:YES completion:nil];
			return;
		}
		
		// 地址不为空
		if ([NSString isEmpty:address.text]) {
			[self presentViewController:[LZCTools alertMessage:@"店铺地址不可为空"] animated:YES completion:nil];
			return;
		}
	}
	else {
		shopOrCompanyName = [self.view viewWithTag:11];
		realName = [self.view viewWithTag:12];
		idCard = [self.view viewWithTag:13];
		licenseCode = [self.view viewWithTag:14];
		
		// 公司不为空
		if ([NSString isEmpty:shopOrCompanyName.text]) {
			[self presentViewController:[LZCTools alertMessage:@"公司名不可为空"] animated:YES completion:nil];
			return;
		}
		// 营业执照不为空
		if ([NSString isEmpty:licenseCode.text]) {
			[self presentViewController:[LZCTools alertMessage:@"营业执照编码不可为空"] animated:YES completion:nil];
			return;
		}
	}

    // 姓名不为空
    if ([NSString isEmpty:realName.text]) {
        [self presentViewController:[LZCTools alertMessage:@"姓名不可为空"] animated:YES completion:nil];
        return;
    }

    // 身份证不为空
    if ([NSString isEmpty:idCard.text]) {
        [self presentViewController:[LZCTools alertMessage:@"身份证不可为空"] animated:YES completion:nil];
        return;
    }
    // 身份证验证
    if (![NSString isValidateIdentityCard:idCard.text]) {
        [self presentViewController:[LZCTools alertMessage:@"您输入的不是身份证号"] animated:YES completion:nil];
        return;
    }
	
    // 几张图片
    NSLog(@"图片张数 %@", self.imgStrArr);
    
    for (int i = 0; i < self.imgStrArr.count; i++) {
        if ([self.imgStrArr[i] isEqualToString:[NSString stringWithFormat:@"%d", i]]) {
            [self presentViewController:[LZCTools alertMessage:@"图片不可以为空"] animated:YES completion:nil];
            return;
        }
    }
    
    NSDictionary *param;
    if ([self.roleToApply isEqual:@2]) {
        param = @{
                  @"role":self.roleToApply,
                  @"realname":realName.text,
                  @"id_no":idCard.text,
                  @"face_pic":self.imgStrArr[0],
                  @"unface_pic":self.imgStrArr[1],
                  @"real_pic":self.imgStrArr[2]
                  };
    }
	else if ([self.roleToApply isEqual:@3]) {
		NSLog(@"第5张图是%@", self.imgStrArr[4]);
		param = @{
				  @"role":self.roleToApply,
				  @"realname":realName.text,
				  @"id_no":idCard.text,
				  @"face_pic":self.imgStrArr[0],
				  @"unface_pic":self.imgStrArr[1],
				  @"real_pic":self.imgStrArr[2],
				  @"license_pic":self.imgStrArr[3],
				  @"license_coding":licenseCode.text,
				  @"address":address.text,
				  @"name":shopOrCompanyName.text,
				  @"shop_logo":self.imgStrArr[4],
				  @"lat":self.lat,
				  @"lng":self.lng
				  };
		NSLog(@"the param is %@", param);
	}
	else {
		param = @{
				  @"role":self.roleToApply,
				  @"realname":realName.text,
				  @"id_no":idCard.text,
				  @"face_pic":self.imgStrArr[0],
				  @"unface_pic":self.imgStrArr[1],
				  @"real_pic":self.imgStrArr[2],
				  @"license_pic":self.imgStrArr[3],
				  @"license_coding":licenseCode.text,
				  @"name":shopOrCompanyName.text
				  };
	}
    
    
    [[NetworkTool sharedTool] requestWithName:@"提交实名认证" URLString:APICertifications parameters:param method:@"POST" callBack:^(id responseObject) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)picAction:(UIButton *)sender {
    
    self.imgTag = sender.tag;
    NSLog(@"%ld", self.imgTag);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"从相册中选择");
        
        self.picker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"拍照");
        
        self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark ==========照相机相册功能==========
/**
 *  配置图片选择器
 */
-(void)createImgPicker {
    self.picker = [[UIImagePickerController alloc]init];
    self.picker.delegate = self;
    self.picker.allowsEditing = YES;
	self.picker.navigationBar.tintColor = [UIColor blackColor];
}

/**
 *  当用户选取完成后调用
 *
 *  @param picker 图片选择器对象
 *  @param info   返回用户所选择的媒体信息
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // 判断选择的媒体类型是否为图片
    if ([mediaType isEqualToString:@"public.image"]) {
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
            
            //如果是 来自照相机的image，那么先保存
            UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
            UIImageWriteToSavedPhotosAlbum(original_image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            
        }
        
        //获得编辑过的图片
        UIImage *image = [[info objectForKey: @"UIImagePickerControllerEditedImage"] copy];
        
        [self updateCover:image];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

/**
 *  将图片保存到iPhone本地相册
 *  UIImage *image            图片对象
 *  id completionTarget       响应方法对象
 *  SEL completionSelector    方法
 *  void *contextInfo
 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    
}

//如果这是一个modalViewController，需要dismiss 它发了个cancel消息，必须关闭它
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark ==========网络请求==========
- (void)updateCover:(UIImage *)img {
    
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    NSDictionary *dict = @{
                           @"file[]":@[]
                           };
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [afn POST:APIImages parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        // 这里的_photoArr是你存放图片的数组
        NSData *imageData = UIImageJPEGRepresentation(img, 0.8);
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        /*
         *该方法的参数
         1. appendPartWithFileData：要上传的照片[二进制流]
         2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
         3. fileName：要保存在服务器上的文件名
         4. mimeType：上传的文件的类型
         */
        [formData appendPartWithFileData:imageData name:@"pic[]" fileName:fileName mimeType:@"image/jpeg"]; //
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
        //        return [obj valueForKey:@"payload"];
        NSArray *imgArr = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"images"];
        NSLog(@"上传图片 success = %@", imgArr);
        
//        [self.imgStrArr replaceObjectAtIndex:self.imgTag-31 withObject:responseObject[@"resources"][0]];
        [self.imgStrArr replaceObjectAtIndex:self.imgTag-31 withObject:imgArr[0]];
        NSLog(@"%@", self.imgStrArr);
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        UIButton *imgBtn = (UIButton *)[self.view viewWithTag:self.imgTag];
        [imgBtn setBackgroundImage:img forState:UIControlStateNormal];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传图片 failure = %@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self presentViewController:[LZCTools AFNErrorAlert:error] animated:YES completion:nil];
    }];
}

/**
 更新用户信息
 */
- (void)updateUserInfo {
	
	[[NetworkTool sharedTool] requestWithName:@"获取用户信息" URLString:APIUser parameters:nil method:@"GET" callBack:^(id responseObject) {
		NSDictionary *userDict = [responseObject valueForKey:@"data"];
		SetUserDefaule(userDict, USERINFO);
		NSLog(@"user info in per is %@", userDict);
		if ([GetUserDefaule(USERINFO)[@"role"] integerValue] == 0) {
			[self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
			return;
		}
	}];
}

- (void)getLocate:(NSNotification *)info{
	AMapTip *tip = info.userInfo[@"tip"];
	NSNumber *lat = [[NSNumber alloc] initWithDouble:tip.location.latitude];
	NSNumber *lng = [[NSNumber alloc] initWithDouble:tip.location.longitude];
	self.lat = lat;
	self.lng = lng;
	NSLog(@"纬度：%@，经度：%@", self.lat, self.lng);
	UITextField *address = [self.view viewWithTag:15];
	address.text = tip.address;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
